<?php
/**
 * Action helper for protecting against CSRF
 *
 * @author Tandat
 */
class D_Helper_Csrf extends Zend_Controller_Action_Helper_Abstract
{
	protected $_session = null;
	
	/**
	 * The name of the form element which contains the key
	 * @var string
	 */
	protected $_keyName = 'csrf';
	
	public $_token = '';
	/**
	 * How long until the csrf key expires (in seconds)
	 * @var int
	 */
	
	protected $_expiryTime = 300;
	
	protected $_previousToken = '';
	
	public function __construct()
	{
		$this->_session = new Zend_Session_Namespace('CsrfProtect');
		
	}
		
	public function initToken(){
		if($this->checkExitToken()){
			$this->_token = $this->getSessionToken();
		}else{
			$this->_initializeTokens();
		}
		D_Utils::view()->token = $this->_token;
	}
	
	public function checkExitToken(){
		$token = $this->getRequest()->getParam('token');
		if(isset($token))
			return true;
		return false;
	}
	
	function getSessionToken(){
		return $this->_session->key;
	}
	/**
	 * Set the expiry time of the csrf key
	 * @param int $seconds expiry time in seconds. Set 0 for no expiration
	 */
	public function setExpiryTime($seconds)
	{
		$this->_expiryTime = $seconds;
		return $this;
	}

	/**
	 * Set the name of the csrf form element
	 * @param string $name
	 */
	public function setKeyName($name)
	{
		$this->_keyName = $name;
		return $this;
	}
	
	
	public function getToken()
	{
		return $this->_token;
	}
	
	/**
	 * Checks if value is the valid token for the previous request
	 * @param string $value
	 * @return bool
	 */
	public function isValidToken()
	{
		$hash_session = $this->_session->key;
		$input = $this->getRequest()->getParam('token');
		return $hash_session == $input;
	}
	public function destroy(){
		$this->_session->unsetAll();
	}
	
	/**
	 * Initializes a new token
	 */
	protected function _initializeTokens()
	{
		$this->_previousToken = $this->_session->key;
		
		$newKey = sha1(microtime() . mt_rand());
		
		$this->_session->key = $newKey;
		if($this->_expiryTime > 0)
			$this->_session->setExpirationSeconds($this->_expiryTime);
		
		$this->_token = $newKey;
	}	
}